package org.spring.boot.fusion.auth.server.filter;

import java.io.IOException;
import java.util.Collection;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.spring.boot.fusion.security.properties.FusionTokenProperties;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.filter.OncePerRequestFilter;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class FusionOnlyUserFilter extends OncePerRequestFilter {

	private TokenStore tokenStore;

	private FusionTokenProperties tokenConfigProperties;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (tokenConfigProperties.isLoginNumberOnly()) {
			String headerUsername = tokenConfigProperties.getUsername();
			String username = request.getParameter("username");
			Collection<OAuth2AccessToken> findTokensByClientIdAndUserName = tokenStore.findTokensByClientIdAndUserName(headerUsername, username);
			for (OAuth2AccessToken oAuth2AccessToken : findTokensByClientIdAndUserName) {
				tokenStore.removeAccessToken(oAuth2AccessToken);
				tokenStore.removeRefreshToken(oAuth2AccessToken.getRefreshToken());
			}
		}
		filterChain.doFilter(request, response);
	}

}
